/**
 * Copyright (c) 2011-2013, kidzhou 周磊 (zhouleib1412@gmail.com)
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.jfinal.ext.plugin.jms.hanlder;

import com.jfinal.ext.plugin.jms.JMSConstants;
import com.jfinal.log.Log;

import javax.jms.Message;
import javax.jms.ObjectMessage;


/**
 * 消费者
 * 注册jms.properties中配置的Resolver消费者
 */
public class CustomReceive implements IMessageHandler {

    protected final Log logger = Log.getLog(getClass());

    private ReceiveResolverFactory receiveResolverFactory;


    public CustomReceive(ReceiveResolverFactory receiveResolverFactory) {
        this.receiveResolverFactory = receiveResolverFactory;
    }


    @Override public void handleMessage(Message message) {
        try {
            int messageType = message.getIntProperty(JMSConstants.JMS_MESSAGE_TYPE);
            ObjectMessage objMsg = (ObjectMessage) message;
            logger.debug("msgType " + messageType + " objMsg :" + objMsg);
            IReceiveResolver resolver =
                    this.receiveResolverFactory.createReceiveResolver(new Integer(messageType));
            if (resolver == null) {
                logger.error("cant find  ReceiveResolver with messageType = " + messageType);
                return;
            }
            resolver.resolve(objMsg.getObject());
        }
        catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }
}
